package com.wisezone.springmvc.controller;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;
import com.wisezone.springmvc.entity.User;

@Controller
public class JsonController {

	// {"id":0,"userName":"张三","passWord":"123"}
	@RequestMapping(value = "/user_json", method = RequestMethod.GET)
	public void getUserJson(PrintWriter pw, HttpServletResponse response) {
		response.setCharacterEncoding("UTF-8"); // ajax请响应中文乱码，乱码过滤不起作用,将其放到请求方法最前面;
		User user = new User("张三", "123");
		Gson gson = new Gson();
		String jsonUser = gson.toJson(user);
		System.out.println(jsonUser);
		pw.print(jsonUser);
	}
	
	@ResponseBody
	@RequestMapping(value = "/user_json1", method = RequestMethod.GET)
	public User getUserJson() {
		User user = new User("张三", "123");
		return user;
	}

	@ResponseBody
	@RequestMapping(value = "/user_json2", method = RequestMethod.GET)
	public List<User> getUserJsonList() {
		User user1 = new User(1,"张三", "123");
		User user2 = new User(2,"李四", "abc");
		List<User> userlist = new ArrayList<>();
		userlist.add(user1);
		userlist.add(user2);
		return userlist;
	}
}
